import { setToken, removeToken, setUserInfo } from '@/utils/auth'
import router, { resetRouter } from '@/router'
import { login, getPermissionRoles } from '@/api/license/author'
import axios from 'axios'

const state = {
    token: '',
    userInfo: {},
    roles: []
}

const mutations = {
    SET_TOKEN: (state, token) => {
        state.token = token
    },
    SET_USERINFO: (state, userInfo) => {
        console.log(userInfo)
        state.userInfo = userInfo
    },
    SET_ROLES: (state, roles) => {
        state.roles = roles
    }
}

const actions = {
    // 登录
    login({ commit }, { username: userName, password }) {
        return new Promise((resolve, reject) => {
            console.log(process.env)
            login({ userName, password }).then(res => {
                const { status: code, obj: response, msg } = res
                if (code !== 200) return reject(msg)
                commit('SET_TOKEN', response.token)
                commit('SET_USERINFO', response)
                setUserInfo(response)
                setToken(response.token, 999)
                resolve()
            }).catch((error) => reject(error))

        })
    },

    // 获取基础信息
    getInfo({ commit, state }) {
        return new Promise((resolve, reject) => {
            if (process.env.VUE_APP_FLAG == 'dev') {
                axios.get('/mocks/asyncRouter/routes.json').then(res => {
                    const { status: code, data: roles } = res
                    console.log('获取权限路由')
                    if (code !== 200) return reject('获取权限失败!')
                    if (!roles || roles.length <= 0) return reject('该用户未拥有权限,请联系管理员!')
                    // commit('SET_USERINFO', userinfo)
                    commit('SET_ROLES', roles)
                    resolve(roles)
                })
            } else {
                getPermissionRoles().then(res => {
                    const { status: code, obj: roles, msg } = res
                    console.log('获取权限路由')
                    if (code !== 200) return reject(msg)
                    if (!roles || roles.length <= 0) return reject('该用户未拥有权限,请联系管理员!')
                    // commit('SET_USERINFO', userinfo)
                    commit('SET_ROLES', roles)
                    resolve(roles)
                }).catch(() => reject())
            }

        })
    },

    // 登出
    logout({ commit, state }) {
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                commit('SET_TOKEN', '')
                commit('SET_ROLES', [])
                removeToken()
                resetRouter()
                resolve()
            }, 0)
        })
    },

    // 移除token
    resetToken({ commit }) {
        return new Promise((resolve) => {
            commit('SET_TOKEN', '')
            commit('SET_ROLES', [])
            removeToken()
            resetRouter()
            resolve()
        })
    },

    //  动态修改路由权限
    changeRoles({ commit, dispatch }, role) {
        return new Promise(async (resolve) => {
            const token = role + '-token'

            commit('SET_TOKEN', token)
            setToken(token)

            const { roles } = await dispatch('getInfo')

            resetRouter()

            // generate accessible routes map based on roles
            const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })

            // dynamically add accessible routes
            router.addRoutes(accessRoutes)

            // reset visited views and cached views
            dispatch('tagsView/delAllViews', null, { root: true })

            resolve()
        })
    }
}

export default {
    namespaced: true,
    state,
    mutations,
    actions
}
